package com.self.campussecondhandmarket.conf;

import com.self.campussecondhandmarket.common.BaseContext;
import com.self.campussecondhandmarket.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Author: Vincent
 * <p> DateTime: 2024/8/5 21:07
 * <p> Description: jwt拦截器配置
 * <p>
 **/

@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.info("开始进行令牌校验");
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		try {
			
			String token = request.getHeader("token");
			Claims claims = JWTUtil.parseToken(token);
			
			if (token == null || claims == null) {
				return false;
			}
			BaseContext.setId((Long) claims.get("id"));
			
		} catch (Exception e) {
			log.error("令牌校验错误,错误信息为: {}", e.getMessage());
			return false;
		}
		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		BaseContext.removeId();
	}
}
